package org.example.project.common.middleware.controller;

import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.example.project.common.contant.R;
import org.example.project.common.middleware.constant.ApiRequestMapping;
import org.example.project.common.middleware.service.ElasticsearchIndexService;
import org.example.project.common.web.RestCrudController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.data.elasticsearch.core.query.AliasQuery;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author wenxy
 * @date 2020/10/21
 */
@RestController
@RequestMapping(ApiRequestMapping.ELASTICSEARCH_API)
@ConditionalOnClass(RestHighLevelClient.class)
public class ElasticsearchApiController implements RestCrudController<String, String> {

    @Autowired
    ElasticsearchIndexService elasticsearchIndexService;

    /**
     * getDtoById
     *
     * @param s identifier
     * @return R<DTO>
     * @see R
     */
    @Override
    public R<String> getById(String s) {
        throw new UnsupportedOperationException();
    }

    @PostMapping("/index")
    public R<String> createIndex(String index) {
        elasticsearchIndexService.createIndex(index);
        return R.success();
    }

    @DeleteMapping("/index/{index}")
    public R<String> deleteIndex(@PathVariable String index) {
        elasticsearchIndexService.deleteIndex(index);
        return R.success();
    }

    @GetMapping("/index/{index}/exists")
    public R<Boolean> indexExists(@PathVariable String index) {
        Boolean b = elasticsearchIndexService.indexExists(index);
        return R.success(b);
    }

    @GetMapping("/index/{index}/mapping")
    public R<Map<String, Object>> getMapping(@PathVariable String index) {
        Map<String, Object> mapping = elasticsearchIndexService.getMapping(index);
        return R.success(mapping);
    }

    @GetMapping("/index/{index}/setting")
    public R<Map<String, Object>> getSetting(@PathVariable String index) {
        Map<String, Object> mapping = elasticsearchIndexService.getSettings(index);
        return R.success(mapping);
    }

    @GetMapping("/index/{index}/alias")
    public R<List<AliasMetaData>> getAliasMetaData(@PathVariable String index) {
        List<AliasMetaData> aliasMetaData = elasticsearchIndexService.queryForAlias(index);
        return R.success(aliasMetaData);
    }

    @DeleteMapping("/{index}/alias")
    public R<Boolean> removeAliasMetaData(@RequestBody AliasQuery query) {
        boolean b = elasticsearchIndexService.removeAlias(query);
        return R.success(b);
    }

}
